/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
const G = 1024 * 1024
const M = 1024
const KB = 1

export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * 获取序列字符串
 * @param {*} obj
 */
export function params2qs(obj) {
  const s = []
  const add = (key, value) => {
    s.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
  }
  // eslint-disable-next-line
  for (let i in obj) {
    obj[i] !== null && obj[i] !== undefined && add(i, obj[i])
  }
  return s.join('&')
}

export const getURLParameters = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => (
      // eslint-disable-next-line no-sequences
      (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a
    ),
    {}
  )

export const getUrlparam = function(param) {
  const reg = new RegExp('(^|&)' + param + '=([^&]*)(&|$)')
  const r = window.location.search.substr(1).match(reg) || window.location.hash.substring((window.location.hash.search(/\?/)) + 1).match(reg)
  if (r != null) {
    return decodeURIComponent(r[2])
  }
  return ''
}

export const getParameter = function(name, str) {
  str = str || location.href
  const r = new RegExp("(\\?|#|&)" + name + "=([^&#]*)(&|#|$)")
  const m = str.match(r)
  const result = decodeURIComponent(!m ? "" : m[2])
  return result
}

/**
 * 为链接注入query参数
 * @param {String} url 地址
 * @param {Object} obj 对象
 */
export function injectQueryString(url = window.location.href, obj = {}) {
  const hashIndex = url.indexOf('#')
  const qsIndex = url.indexOf('?')

  const str = qsIndex !== -1 ? url.substring(0, qsIndex) : url
  const hash = hashIndex !== -1 ? url.substr(hashIndex) : ''

  const params = param2Obj(url) || {}
  Object.keys(obj).forEach((k) => {
    params[k] = obj[k]
  })

  return `${str}?${params2qs(params)}${hash}`
}

export const handleTransformSize = size => {
  if (size >= G) {
    return (size / G).toFixed(2) + 'G'
  }
  if (size >= M) {
    return (size / M).toFixed(2) + 'MB'
  }
  return (size / KB).toFixed(2) + 'KB'
}

export const on = (function() {
  if (window.addEventListener) {
    return function(element, event, handler) {
      if (element && event && handler) {
        element.addEventListener(event, handler, false)
      }
    }
  } else {
    return function(element, event, handler) {
      if (element && event && handler) {
        element.attachEvent('on' + event, handler)
      }
    }
  }
})()

export const off = (function() {
  if (window.removeEventListener) {
    return function(element, event, handler) {
      if (element && event) {
        element.removeEventListener(event, handler, false)
      }
    }
  } else {
    return function(element, event, handler) {
      if (element && event) {
        element.detachEvent('on' + event, handler)
      }
    }
  }
})()

export const requestAnimFrame = (function() {
  return (
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    function(callback) {
      window.setTimeout(callback, 1000 / 60)
    }
  )
})()

export const cancelRequestAnimFrame = function(fn) {
  if (fn) {
    const cancel =
      window.cancelAnimationFrame ||
      window.webkitCancelAnimationFrame ||
      window.mozCancelAnimationFrame
    cancel(fn)
  }
}

export function throttle(delay, noTrailing, callback, debounceMode) {
  let timeoutID
  let cancelled = false
  let lastExec = 0

  function clearExistingTimeout() {
    if (timeoutID) {
      clearTimeout(timeoutID)
    }
  }
  function cancel() {
    clearExistingTimeout()
    cancelled = true
  }
  if (typeof noTrailing !== 'boolean') {
    debounceMode = callback
    callback = noTrailing
    noTrailing = undefined
  }
  function wrapper(...arguments_) {
    const self = this
    const elapsed = Date.now() - lastExec

    if (cancelled) {
      return
    }
    function exec() {
      lastExec = Date.now()
      callback.apply(self, arguments_)
    }
    function clear() {
      timeoutID = undefined
    }

    if (debounceMode && !timeoutID) {
      exec()
    }

    clearExistingTimeout()

    if (debounceMode === undefined && elapsed > delay) {
      exec()
    } else if (noTrailing !== true) {
      timeoutID = setTimeout(
        debounceMode ? clear : exec,
        debounceMode === undefined ? delay - elapsed : delay
      )
    }
  }
  wrapper.cancel = cancel
  return wrapper
}
